package com.dty.factory;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dty.po.MyBean;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

/**
 * 获取配置文件
 * 解析配置文件,将bean标签解析成MyBean对象,并将所有的对象放到list中
 * 遍历列表实例化bean对象,并将<id,instance>放到map中
 * 通过getBean方法返回bean实例
 */
public class ClassPathXmlApp implements MyBeanFactory {
  // 解析好的bean标签集合
  private List<MyBean> beanList = null;

  private Map<String, Object> beanMap = new HashMap<String, Object>();

  public ClassPathXmlApp(String fileName) throws DocumentException {
    this.parseXml(fileName);
    this.instanceBean();
  }

  private void instanceBean() {
    if (this.beanList != null && this.beanList.size() > 0) {
      for (MyBean myBean : beanList) {
        String id = myBean.getId();
        String classPathName = myBean.getClassPathName();
        System.out.println(id + "---" + classPathName);
        try {
          Object object = Class.forName(classPathName).newInstance();
          this.beanMap.put(id, object);

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 解析xml文件
   * 
   * @param fileName
   * @throws DocumentException
   */
  private void parseXml(String fileName) throws DocumentException {
    SAXReader saxReader = new SAXReader();
    URL url = this.getClass().getClassLoader().getResource(fileName);
    Document dc = saxReader.read(url);
    // 通过xpath语法解析dc
    XPath xPath = dc.createXPath("beans/bean");
    List<Element> elementList = xPath.selectNodes(dc);
    if (elementList != null && elementList.size() > 0) {
      this.beanList = new ArrayList<MyBean>();
      for (Element element : elementList) {
        String id = element.attributeValue("id");
        String classPathName = element.attributeValue("class");
        MyBean mybean = new MyBean(id, classPathName);
        this.beanList.add(mybean);
      }
    }
  }

  public Object getBean(String id) {

    return this.beanMap.get(id);
  }

}
